#include<cstdio>
const int maxn=50010;
int p[maxn+1],r[maxn+1],n,k,ans=0;
int find(int x)
{
	int t;
	if(p[x]!=x)
	{
		t=p[x];
		p[x]=find(p[x]);
		r[x]=(r[x]+r[t])%3;
	}
	return p[x];
}
void merge(int a,int b,int d,int pp,int qq)
{
	p[pp]=qq;
	r[pp]=(r[b]-r[a]+d+2)%3;
}
int main()
{
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++){p[i]=i;r[i]=0;}
	for(int i=1;i<=k;i++)
	{
		int dd,x,y;
		scanf("%d%d%d",&dd,&x,&y);
		int pp=find(x);
		int qq=find(y);
		if(x>n||y>n){ans++;continue;}
		if(pp!=qq)merge(x,y,dd,pp,qq);
		else if(x==y&&dd==2||(r[x]-r[y]+4)%3!=dd)ans++;
	}
	printf("%d\n",ans);
	return 0;
}



